package com.dy.yunying.biz.controller.manage;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dy.yunying.api.entity.WanCdkConfig;
import com.dy.yunying.api.resp.WanCdkExportData;
import com.dy.yunying.biz.service.manage.WanCdkConfigService;
import com.dy.yunying.biz.utils.DateUtils;
import com.dy.yunying.biz.utils.ExportUtils;
import com.dy.yunying.biz.utils.MapUtils;
import com.google.api.client.util.Lists;
import com.pig4cloud.pig.common.core.util.R;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 代金券导出数据配置表
 * @author  chenxiang
 * @version  2022-04-18 16:23:05
 * table: cdk_grant_config
 */
@Log4j2
@RestController
@RequiredArgsConstructor
@RequestMapping("/cdkConfig")
public class WanCdkConfigController {
	
    private final WanCdkConfigService wanCdkConfigService;

	/**
	 * 列表
	 * @return
	 */
	@RequestMapping("/getList")
	public R getList(){
		return R.ok(wanCdkConfigService.list(Wrappers.<WanCdkConfig>lambdaQuery().eq(WanCdkConfig::getDeleted,0)));
	}

	/**
	 * 导出
	 * @param record
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/exportData")
	public void exportExcel(@RequestBody WanCdkConfig record, HttpServletRequest request, HttpServletResponse response){
		try {
			List<WanCdkExportData> resultList = Lists.newArrayList();
			WanCdkConfig wanCdkConfig = wanCdkConfigService.getById(record.getId());
			if (Objects.nonNull(wanCdkConfig)){
				resultList = wanCdkConfigService.getData(wanCdkConfig);
			}
			if (CollectionUtils.isEmpty(resultList)){
				WanCdkExportData exportData = new WanCdkExportData();
				exportData.setUserName("没有匹配的数据");
				resultList.add(exportData);
			}
			// list对象转listMap
			List<Map<String, Object>> resultListMap = MapUtils.objectsToMaps(resultList);
			String titles = "账号,区服,角色ID,等级,充值金额";
			String columns = "userName,areaId,roleId,roleLevel,rechargeAmount";
			String fileName = Objects.nonNull(wanCdkConfig) ? wanCdkConfig.getTitle() : "未导出数据";
			// 导出
			ExportUtils.exportExcelData(request, response,fileName + "-" + DateUtils.dateToString(new Date(), DateUtils.YYYYMMDD_HH_MM_SS) + ".xlsx", "用户数据",titles, columns, resultListMap);
		} catch (Exception e) {
			log.error("cdk导出数据异常：" + e.getMessage());
		}
	}
}


